<?php
namespace app\index\controller;
use app\index\common;
use app\index\controller\Log\InsertLog as IL;
use app\index\controller\Log\OperationLog as OL;
use app\index\controller\Product;
use app\index\service\OrderService;
use think\Controller;
use think\Db;
use think\Request;

class Order extends Controller {
	/**
	 * 2018-04-19
	 * 曹振威
	 * 订单列表
	 * @return json
	 */
	public function order_list($action = '') {
		$user_id = $this->user_id;
		$system_id = $this->system_id;
		$user = $this->user;
		$where_arr = array();
		$this->business_id ? $where_arr['or.business_id'] = $this->business_id : exit(json_encode(array('code' => 20021, 'msg' => '非法操作', 'data' => '')));
		$this->store_id ? $where_arr['or.store_id'] = $this->store_id : FALSE;
		$product_name = input('product_name');
		$cutomer = input('cutomer');
		$procurement_status = input('procurement_status');
		$sale_system = input('sale_system');
		$is_shelf = input('is_shelf');
		if (isset($is_shelf) && $is_shelf != '') {
			$where_arr['o.status'] = $is_shelf;
		}
		if (isset($procurement_status) && $procurement_status != '') {
			$where_arr['p.procurement_status'] = $procurement_status;
		}
		if (isset($sale_system) && $sale_system != '') {
			$where_arr['o.sale_system'] = $sale_system;
		}

		//input('brand') ? $where_arr['p.systematics_id'] = input('brand'): FALSE;
		$brand = input('brand');
		if (!empty($brand)) {
			$brand_ids = OrderService::getBrandIds($brand);
			$where_arr['p.systematics_id'] = array('in', $brand_ids);
		}

		$begin = input('add_time_begin');
		$end = input('add_time_end');
		if ($begin && $end) {
			$end = date('Y-m-d', strtotime("$end +1 day"));
			$where_arr['o.createtime'] = array('between', "$begin,$end");
		} elseif ($begin && !$end) {
			$where_arr['o.createtime'] = array('EGT', "$begin");
		} elseif (!$begin && $end) {
			$end = date('Y-m-d', strtotime("$end +1 day"));
			$where_arr['o.createtime'] = array('GLT', "$end");
		}
		//财务确认时间
		$begin_confirm = input('begin_confirm');
		$end_confirm = input('end_confirm');
		if ($begin_confirm && $end_confirm) {
			$where_arr['or.is_confirm'] = 1;
			$where_arr['or.createtime'] = array('between', "$begin_confirm,$end_confirm");
		} elseif ($begin_confirm && !$end_confirm) {
			$where_arr['or.is_confirm'] = 1;
			$where_arr['or.createtime'] = array('EGT', "$begin_confirm");
		} elseif (!$begin_confirm && $end_confirm) {
			$where_arr['or.is_confirm'] = 1;
			$where_arr['or.createtime'] = array('GLT', "$end_confirm");
		}
		$type = input('type'); // 1:我的订单；2：全部订单
		if ($type == 1) {
			$where_arr['or.staff_id'] = $user_id;
		}
		if ($product_name) {
			$where_arr['p.product_name|p.product_sn|p.product_source|o.batchcode'] = ['LIKE', '%' . $product_name . '%'];
		}
		if ($cutomer) {
			$where_arr['or.customer_name|ui.name|ui.wechat|u.phone'] = ['LIKE', '%' . $cutomer . '%'];
		}
		$where_arr['or.state'] = 0;
		input('sord') == 1 ? $order = 'o.createtime asc' : $order = 'o.createtime desc';
		$order_type = input('order_type', 0); // 0:门店订单；1：平台订单
		input('staff_id') ? $where_arr['or.staff_id'] = input('staff_id') : FALSE;
		$where_arr['o.type'] = $order_type;
		$where_arr['or.state'] = 0;
		$where_arr['or.is_nursing'] = 0;
		$field = 'or.id,or.quantity,o.type,o.total_price,o.total_rebate,o.total_fare,'
			. 'or.pequired_points,or.earn_points,or.total_commission,or.quantity,or.pay_reatetime,'
			. 'o.batchcode,or.customer_name,or.total_profit,'
			. 'or.real_profit,p.product_condition,pf.value product_condition_value,or.product_id,p.product_name,p.product_sn,'
			. 's.store_name,o.status,sc.value status_value,or.createtime,p.procurement_status, ps.value procurement_value,or.price,'
			. 'or.cost_price pre_price,p.cost_price,or.peer_price,'
			. 'or.other_fee,p.product_source,p.pic_url,or.deposit,st.name staff_name,or.is_confirm,p.additional,'
			. 'or.is_prepay,p.sale_share,p.receive_share,o.sale_system,sp.value system_value,p.systematics_id';
		if (empty($action)) {
			$row = Db::table('orders_info')->alias('or')
				->join('orders o', 'or.batchcode=o.batchcode', 'LEFT')
				->join('sales_condition sc', 'sc.id=o.status', 'LEFT')
				->join('store s', 's.user_id=or.store_id', 'LEFT')
				->join('product p', 'or.product_id=p.id', 'LEFT')
				->join('product_fineness pf', 'p.product_condition = pf.id', 'LEFT')
				->join('perchase_source ps', 'p.procurement_status = ps.id', 'LEFT')
				->join('user_info ui', 'or.user_id=ui.user_id', 'LEFT')
				->join('users u', 'u.id=or.user_id', 'LEFT')
				->join('staff st', 'st.user_id=or.staff_id', 'LEFT')
				->join('sales_plateform sp', 'o.sale_system = sp.id', 'LEFT')
				->where($where_arr)
				->order($order)
				->field($field)
				->paginate()->toArray();
			foreach ($row['data'] as $okey => $ovalue) {
				$product = new Product();
				$systematics_arr = $product->set_product_name($ovalue['systematics_id']);
				if (!$systematics_arr['data']) {
					$row['data'][$okey]['pre_name'] = '';
				} else {
					$row['data'][$okey]['pre_name'] = $systematics_arr['data'];
				}
			}
			$date = array('code' => 666, 'msg' => '订单列表获取成功', 'data' => $row);
			IL::insert('log', [
				'user_id' => $this->user_id,
				'operation_user' => $this->user['name'],
				'operation_name' => '查看',
				'operation_type' => 1,
				'operation_content' => '查看订单列表',
				'ip' => Request()->ip(),
				'createtime' => date('Y-m-d H:i:s'),
				'state' => 1,
			]);
		} elseif ($action = 'order_excel') {
			$date = Db::table('orders_info')->alias('or')
				->join('orders o', 'or.batchcode=o.batchcode', 'LEFT')
				->join('store s', 's.user_id=or.store_id', 'LEFT')
				->join('product p', 'or.product_id=p.id', 'LEFT')
				->join('user_info ui', 'o.user_id=ui.user_id', 'LEFT')
				->join('users u', 'u.id=o.user_id', 'LEFT')
				->join('staff st', 'st.user_id=or.user_id', 'LEFT')
				->join('sales_plateform sp', 'o.sale_system = sp.id', 'LEFT')
				->where($where_arr)
				->order($order)
				->field($field)
				->select();
		}

		return $date;
	}

	/**
	 * 2018-04-19
	 * 曹振威
	 * 订单详情
	 * @return string
	 */
	public function order_info(Product $product) {
		$where = array();
		$user_id = $this->user_id;
		if (!$this->business_id) {
			$date = array('code' => 20020, 'msg' => '非商户', 'data' => '');
			exit(json_encode($date));
		}
		$where['or.business_id'] = $this->business_id;
		input('id') ? $where['or.id'] = input('id') : exit(json_encode(array('code' => 20021, 'msg' => '非法操作', 'data' => '')));
		$type = input('type', 0);
		if ($type == 0) {
			// 销售订单
			$filed = 'or.id,or.batchcode,or.pay_batchode,or.info_batchcode,or.product_id,'
				. 'or.product_name,or.price,p.cost_price,or.peer_price,or.fare,or.status,sc.value status_value,'
				. 'or.pequired_points,or.earn_points,or.total_commission,or.quantity,or.pay_reatetime,'
				. 'or.rights_time,or.refund_time,or.createtime,or.remark,or.payment_status,p.product_sn,o.order_source,'
				. 'or.customer_name,u.phone,or.is_prepay,or.deposit,or.shipping_sn,or.sale_date,or.nursing_fee,or.other_fee,'
				. 'p.pic_url,or.is_nursing,st.user_id staff_id,st.name staff_name,o.pay_code,pm.value payment_value,o.shipping_code,'
				. 'sto.user_id store_id,sto.store_name,s.id systematics_id,p.sale_share,'
				. 'p.receive_share,o.sale_system,sp.value system_value,'
				. 'p.product_condition,pf.value product_condition_value,p.brand_id,p.type_id,p.category_id';
		} elseif ($type == 1) {
			// 护理订单
			$filed = 'or.id,or.batchcode,or.pay_batchode,or.info_batchcode,or.product_id,'
				. 'or.product_name,or.price,p.cost_price,or.peer_price,or.fare,or.status,nc.value status_value,'
				. 'or.pequired_points,or.earn_points,or.total_commission,or.quantity,or.pay_reatetime,'
				. 'or.rights_time,or.refund_time,or.createtime,or.remark,or.payment_status,p.product_sn,o.order_source,'
				. 'or.customer_name,u.phone,s.id systematics_id,or.nursing_cost,or.nursing_income,or.nursing_fee,'
				. 'or.nursing_remark,or.is_urgent,or.urgent_remark,or.parts,'
				. 'p.pic_url,or.is_nursing,st.user_id staff_id,st.name staff_name,o.pay_code,pm.value payment_value,o.shipping_code,'
				. 'sto.user_id store_id,sto.store_name,or.remark,or.is_prepay,or.deposit,'
				. 'p.sale_share,p.receive_share,o.sale_system,'
				. 'sp.value system_value,p.product_condition,pf.value product_condition_value,p.brand_id,p.type_id,p.category_id';
		}
		$row = Db::table('orders_info')->alias('or')
			->join('orders o', 'or.batchcode=o.batchcode', 'LEFT')
			->join('staff st', 'or.staff_id=st.user_id', 'LEFT')
			->join('users u', 'or.user_id=u.id', 'LEFT')
			->join('product p', 'or.product_id=p.id', 'LEFT')
			->join('systematics s', 'p.systematics_id=s.id', 'LEFT')
			->join('sales_condition sc', 'or.status = sc.id', 'LEFT')
			->join('store sto', 'or.store_id=sto.user_id', 'LEFT')
			->join('nursing_condition nc', 'or.status = nc.id', 'LEFT')
			->join('sales_plateform sp', 'o.sale_system = sp.id', 'LEFT')
			->join('product_fineness pf', 'p.product_condition = pf.id', 'LEFT')
			->join('payment_mode pm', 'o.pay_code = pm.id', 'LEFT')
			->where($where)->field($filed)->find();
		if ($row['system_value'] == '') {
			if ($row['order_source']) {
				$row['order_source'] = (int) $row['order_source'];
				$row['system_value'] = Db::table('sales_plateform')->where('id', $row['order_source'])->value('value');
			}
		}
		if ($row['systematics_id']) {
			$systematics_arr = $product->set_product_name($row['systematics_id']);
			$product_systematics = $product->get_systematics($row['systematics_id']);
		} elseif ($row['brand_id']) {
			$systematics_arr = $product->set_product_name($row['brand_id']);
			$product_systematics = $product->get_systematics($row['brand_id']);
		} elseif ($row['type_id']) {
			$systematics_arr = $product->set_product_name($row['type_id']);
			$product_systematics = $product->get_systematics($row['type_id']);
		} elseif ($row['category_id']) {
			$systematics_arr = $product->set_product_name($row['category_id']);
			$product_systematics = $product->get_systematics($row['category_id']);
		} else {
			$systematics_arr = [];
			$product_systematics = [];
		}
		if (!array_key_exists('data', $systematics_arr)) {
			$row['pre_name'] = '';
		} else {
			$row['pre_name'] = $systematics_arr['data'];
		}
		$row['systematics_info'] = $product_systematics;
		if ($row['is_prepay'] == 1) {
			$total = $row['price'] * $row['quantity']; // 该商品总额
			$row['arrears'] = $total - $row['deposit'];
		}
		if (($type == 0 && $row['is_nursing'] == 1) || ($type == 1 && $row['is_nursing'] == 0)) {
			exit(json_encode(array('code' => 20078, 'msg' => 'type参数有误', 'data' => '')));
		}
		$date = array('code' => 666, 'msg' => '订单详情获取成功', 'data' => $row);
		IL::insert('log', [
			'user_id' => $this->user_id,
			'operation_user' => $this->user['name'],
			'operation_name' => '查看',
			'operation_type' => 1,
			'orderinfo_id' => $row['id'],
			'operation_content' => '查看订单详情',
			'ip' => Request()->ip(),
			'createtime' => date('Y-m-d H:i:s'),
			'state' => 1,
		]);
		return $date;
	}

	/**
	 * 2018-04-20
	 * 曹振威
	 * 订单列表导出
	 */
	public function order_excel() {
		$data = $this->order_list('order_excel');
		$key = [
			'订单类型', '订单号', '产品编号', '产品名称', '产品现价', '成本价', '同行价', '订单总价', '返佣总额', '运费总额', '订单状态', '所需积分', '获得积分', '单个产品总佣金', '产品数量', '支付时间',
		];
		$keyname = array('type', 'batchcode', 'product_id', 'product_name', 'price', 'cost_price', 'peer_price', 'total_price', 'total_rebate', 'total_fare', 'status', 'pequired_points', 'earn_points', 'total_commission', 'quantity', 'pay_reatetime');
		$styleArray = [
			'font' => ['bold' => true],
		];
		common::output_excel($key, $data, $keyname, '订单列表', $styleArray);
	}

	/**
	 * 2019-05-31 czw 改
	 * 2018-04-23 开发日期
	 * 曹振威 开发人
	 * 添加销售订单
	 */
	public function add_sale_order(Product $product, Request $R) {
//        $receive_share=0;
		//        $sale_share=0;
		$data = $R->post();
		$rule = [
			'id' => 'require|number',
			'product_num' => 'require|number|between:1,120',
			'sale_status' => 'require|number|between:1,7',
			'price' => 'require|float',
		];
		$msg = [
			'id.require' => '转为销售订单的商品编号不能为空',
			'id.number' => '商品编号只能是数字',
			'product_num.require' => '商品数量必填',
			'product_num.number' => '商品数量只能是数字',
			'product_num.between' => '商品数量至少为1',
			'sale_status.require' => '销售状态必填',
			'sale_status.number' => '销售状态必须传数字',
			'sale_status.between' => '销售状态必需传1-7数字',
			'price.require' => '商品销售价必填',
			'price.float' => '商品销售价是浮点类型',
		];
		$bool = $this->validate($data, $rule, $msg);
		if ($bool !== true) {
			exit(json_encode(array('code' => 20203, 'msg' => $bool, 'data' => '')));
		}
		// 验证产品是否存在订单且不是退货,如果存在则不能再次销售
		OrderService::check_order($data['id'], $this->business_id);
		// 验证产品是否存在
		$product_info = $product->check_product($data['id']);
		// 验证产品是否可售状态
		OrderService::check_product_sale($data['id'], $this->business_id);
		// 确认库存数量是否足够
		$product->get_stock_status($data['id'], $data['product_num']);
		//订单详情插入值
		$order_info_insert = [
			'system_id' => $this->system_id,
			'business_id' => $this->business_id,
			'store_id' => $this->store_id,
			'product_id' => $data['id'],
			'product_name' => $product_info['product_name'],
			'peer_price' => $product_info['peer_price'],
			'procurement_status' => $product_info['procurement_status'],
			'cost_price' => $product_info['price'],
			'quantity' => $data['product_num'],
			'original_price' => $product_info['cost_price'],
			'price' => $data['price'],
			'status' => $data['sale_status'],
			'createtime' => date('Y-m-d H:i:s'),
			'last_time' => date('Y-m-d H:i:s'),
		];
		//订单表插入值
		$order_insert = [
			'system_id' => $this->system_id,
			'business_id' => $this->business_id,
			'type' => 0, // 门店订单
			'status' => $data['sale_status'],
			'createtime' => date('Y-m-d H:i:s'),
			'quantity' => $data['product_num'],
			'total_price' => (float) $data['price'] * (float) $data['product_num'],
			'last_time' => date('Y-m-d H:i:s'),
		];
		if ($data['phone']) {
			// 验证是否存在客户，存在则返回信息，不存在则增加到user，并且增加到客户customer
			$user = OrderService::check_customer($data['phone'], $this->business_id);
			$order_info_insert['user_id'] = $user['id'];
			$order_info_insert['customer_name'] = $user['name'];
			$order_insert['user_id'] = $user['id'];
		}
		if ($data['sale_system']) {
			$order_insert['sale_system'] = $data['sale_system'];
		}
		if ($data['pay_method']) {
			$order_insert['pay_code'] = $data['pay_method'];
		}
		if ($data['shipping_company']) {
			$order_insert['shipping_code'] = $data['shipping_company'];
		}
		if ($data['shipping_fee']) {
			$order_info_insert['fare'] = $data['shipping_fee'];
		}
		if ($data['shipping_sn']) {
			$order_info_insert['shipping_sn'] = $data['shipping_sn'];
		}
		if ($data['saler']) {
			$order_info_insert['staff_id'] = $data['saler'];
		} else {
			$order_info_insert['staff_id'] = $this->user_id;
		}
		if ($data['deposit'] && $data['deposit'] < $data['price']) {
			$data['sale_status'] = 4;
			$order_info_insert['deposit'] = $data['deposit'];
			$order_info_insert['status'] = $data['sale_status'];
			$order_insert['status'] = $data['sale_status'];
			$order_info_insert['is_prepay'] = 1;
			$total_profit = OrderService::get_total_profit(1, $data['price'], $product_info['cost_price'], $data['other_fee'], $data['nursing_fee'], $product_info['additional']);
			$price = $data['deposit'];
		} else {
			$this->check_deposit($data['deposit'], $data['sale_status']);
			$total_profit = (float) $data['price'] - (float) $product_info['cost_price'];
			$order_info_insert['is_prepay'] = 0;
			$price = $data['price'];
		}
		if ($total_profit['code']) {
			exit(json_encode($total_profit));
		}
		$real_profit = OrderService::get_real_profit($price, $product_info['cost_price'], $data['other_fee'], $data['nursing_fee'], $product_info['additional'], $data['shipping_fee']);
		$order_info_insert['total_profit'] = $total_profit;
		$order_info_insert['real_profit'] = $real_profit;
		if ($data['remark']) {
			$order_info_insert['remark'] = $data['remark'];
		}
		if ($data['nursing_fee']) {
			$order_info_insert['nursing_fee'] = $data['nursing_fee'];
		}
		if ($data['other_fee']) {
			$order_insert['total_fare'] = $data['shipping_fee'];
			$order_info_insert['other_fee'] = $data['other_fee'];
		}

		$type = 0;
		$batchcode = date('Ym') . $this->user_id . $data['id'] . date('d') . date('His');
		$order_info_insert['batchcode'] = $batchcode;
		$order_insert['batchcode'] = $batchcode;
		$order_info_insert['info_batchcode'] = $batchcode . $data['id'];
		OrderService::is_complete($data['sale_status'], $data['price'] * $data['product_num'], $price, $order_info_insert['is_prepay']);
		// 新增订单
		$row_order = Db::table('orders')->insertGetId($order_insert);
		// 新增订单详情
		$row_orders_info = Db::table('orders_info')->insertGetId($order_info_insert);
		if ($row_order && $row_orders_info) {
			// 修改相应的商品状态
			Db::table('product')->where('id', $data['id'])->setField('product_state', $this->change_product_state($data['sale_status'], $data['id']));
			Db::table('product')->where(['id' => $data['id']])->update(['is_onsale' => 0, 'is_network' => 0]);
			$date = array('code' => 666, 'msg' => '添加销售订单成功', 'data' => array('orderinfo_id' => $row_orders_info));

			// 其他同步该商品的商家都要下架并作标注
			OrderService::deSynchroProducts($data['id']);
			$product_info = Db::table('product')->where('id', $data['id'])->find();
			// 创建消息通知
			$description = $product_info['full_name'];
			OrderService::notice_add($this->user_id, 6, 2, $this->business_id, $row_orders_info, $description);

			OL::insert([
				'user_id' => $this->user_id,
				'module' => 'orders',
				'module_id' => $row_order,
				'operation_type' => 1,
				'operation_content' => json_encode(['orders' => Db::table('orders')->where(['id' => $row_order])->find(),
					'orders_info' => Db::table('orders_info')->where(['id' => $row_orders_info])->find(),
					'product' => Db::table('product')->where(['id' => $data['id']])->find(),
				]),
			]);
			OL::insert([
				'user_id' => $this->user_id,
				'module' => 'product',
				'module_id' => $data['id'],
				'operation_type' => 2,
				'operation_content' => json_encode(['orders' => Db::table('orders')->where(['id' => $row_order])->find(),
					'orders_info' => Db::table('orders_info')->where(['id' => $row_orders_info])->find(),
					'product' => Db::table('product')->where(['id' => $data['id']])->find(),
				]),
			]);
		} else {
			$date = array('code' => 20040, 'msg' => '添加销售订单失败', 'data' => '');
		}
		return $date;
	}

	/**
	 * 2018-04-28
	 * 曹振威
	 * 订单删除
	 * @return int
	 */
	public function order_del() {
		$where = array();

		$id = input('order_sn');
		if (!$id) {
			$date = array('code' => 20021, 'msg' => '非法操作', 'data' => '');
			exit(json_encode($date));
		} else {
			if ($this->store_id > 0) {
				$where['store_id'] = $this->store_id;
			}
			if ($this->business_id) {
				$where['business_id'] = $this->business_id;
			}
			$where['state'] = 0;
			$order_ids = explode(",", $id);
			$order = Db::table('orders_info')->where($where)->whereIn('batchcode', $order_ids)->select();
			if (!$order) {
				$date = array('code' => 20068, 'msg' => '不存在该订单', 'data' => '');
				exit(json_encode($date));
			}
			try {
				Db::table('orders_info')->where($where)->whereIn('batchcode', $order_ids)->setField('state', 1);
				Db::table('orders')->whereIn('batchcode', $order_ids)->setField('state', 1);
				$order_id = Db::table('orders')->where($where)->whereIn('batchcode', $order_ids)->field('id')->select();
				$row_orders_info = Db::table('orders_info')->where($where)->whereIn('batchcode', $order_ids)->field('id')->select();
				$date = array('code' => 666, 'msg' => '订单删除成功', 'data' => '');

				// 创建消息通知
				$description = $order_ids;
				OrderService::notice_add($this->user_id, 7, 2, $this->business_id, $row_orders_info['id'], $description, 1, 0);
				foreach ($order_id as $key => $value) {
					OL::insert([
						'user_id' => $this->user_id,
						'module' => 'orders',
						'module_id' => $value,
						'operation_type' => 4,
						'operation_content' => json_encode(['orders' => Db::table('orders')->where(['id' => $value])->find(),
							'orders_info' => Db::table('orders_info')->where(['id' => $row_orders_info])->find(),
						]),
					]);
				}
			} catch (Exception $exc) {
				$date = array('code' => 20063, 'msg' => '订单删除失败' . $exc, 'data' => '');
			}

		}
		return $date;
	}

	/**
	 * 2018-06-05
	 * czw
	 * 追加余款
	 */
	public function append_money() {
		$id = input('id'); // 追加的订单id
		$money = input('deposit');
		$remark = input('remark');
		if ($this->store_id > 0) {
			$where['store_id'] = $this->store_id;
		}
		if ($this->business_id) {
			$where['business_id'] = $this->business_id;
		}
		$where['state'] = 0;
		if (empty($id)) {
			$date = array('code' => 20021, 'msg' => '操作的订单编号不能为空', 'data' => '');
			exit(json_encode($date));
		}
		$product = new Product();
		// 追加完成 则 状态变为  平台未确认   否则 继承订单之前的状态
		$row_origin = Db::table('orders_info')->where('id', $id)->field('status,price,quantity,is_prepay,deposit,batchcode,product_id,other_fee,nursing_cost')->find();
		$product_info = $product->check_product($row_origin['product_id']);
		if ($row_origin['is_prepay'] == 0 || in_array($row_origin['status'], [1, 2, 3, 5, 6, 7])) {
			$date = array('code' => 22222, 'msg' => '该订单非定金支付，不用追加余款', 'data' => '');
			exit(json_encode($date));
		}
		$total = (float) $row_origin['price'] * (int) $row_origin['quantity']; // 该商品总额
		$deposit = (float) $row_origin['deposit'] + (float) $money;
		$real_profit = OrderService::get_real_profit($deposit, $product_info['cost_price'], $row_origin['other_fee'], $row_origin['nursing_cost'], $product_info['additional']);
		if ($deposit == $total) {
			// 追加完成就修改状态为  待发货
			$up = [
				'status' => 2,
				'is_prepay' => 0,
				'deposit' => $deposit,
				'real_profit' => $real_profit,
				'remark' => $remark,
				'last_time' => date('Y-m-d H:i:s'),

			];
			$up_order = [
				'status' => 2,
				'remark' => $remark,
				'last_time' => date('Y-m-d H:i:s'),
			];
		} else {
			$up = [
				'deposit' => $deposit,
				'remark' => $remark,
				'real_profit' => $real_profit,
				'last_time' => date('Y-m-d H:i:s'),
			];
			$up_order = [
				'remark' => $remark,
				'last_time' => date('Y-m-d H:i:s'),
			];
		}
		Db::table('orders_info')->where('id', $id)->update($up);
		$batchcode = Db::table('orders_info')->where('id', $id)->field('id,batchcode,product_id')->find();
		Db::table('orders')->where('batchcode', $batchcode['batchcode'])->update($up_order);

		$date = array('code' => 666, 'msg' => '追加余款成功', 'data' => array('order_id' => $batchcode['id']));
		IL::insert('addmoney', [
			'user_id' => $this->user_id,
			'operation_user' => $this->user['name'],
			'operation_name' => '追加余款',
			'order_id' => $id,
			'add_money' => $money,
			'ip' => Request()->ip(),
			'createtime' => date('Y-m-d H:i:s'),
			'state' => 1,
		]);
		return $date;
	}

	/**
	 * 2018-04-28
	 * 曹振威
	 * 退货/编辑/财务确认
	 */
	public function order_operate(Product $p) {
		$type = input('type'); // 1:编辑；3：退货；4：财务确认
		$id = input('id');
		$remark = input('remark');
		if ($this->store_id > 0) {
			$where['store_id'] = $this->store_id;
		}
		if ($this->business_id) {
			$where['business_id'] = $this->business_id;
		}
		$where['state'] = 0;
		if (empty($id) || empty($type)) {
			$date = array('code' => 20021, 'msg' => '非法操作', 'data' => '');
			exit(json_encode($date));
		}
		if ($type == 1) {
			// 编辑只能编辑售价和销售状态
			$price = input('price');
			$status = input('status');
			if (!isset($price) || !isset($status)) {
				$date = array('code' => 20021, 'msg' => '售价和销售状态都是必填', 'data' => '');
				exit(json_encode($date));
			} else {
				$batchcode = Db::table('orders_info')->where('id', $id)
					->field('batchcode,product_id,price,other_fee,nursing_cost,status,is_prepay,deposit')->find();
				$product = $p->check_product($batchcode['product_id']);
				$total_profit = OrderService::get_total_profit(1, $price, $product['cost_price'], $batchcode['other_fee'], $batchcode['nursing_cost'], $product['additional']);
				if ($batchcode['is_prepay'] == 1) {
					OrderService::is_complete($status, $price, $batchcode['deposit'], $batchcode['is_prepay']);
					$real_profit = OrderService::get_real_profit($batchcode['deposit'], $product['cost_price'], $batchcode['other_fee'], $batchcode['nursing_cost'], $product['additional']);
				} else {
					$this->change_status($batchcode['status'], $status);
					$real_profit = OrderService::get_real_profit($price, $product['cost_price'], $batchcode['other_fee'], $batchcode['nursing_cost'], $product['additional']);
				}
				$row = Db::table('orders_info')->where('id', $id)
					->update(['price' => $price, 'remark' => $remark, 'status' => $status, 'total_profit' => $total_profit, 'real_profit' => $real_profit, 'last_time' => date('Y-m-d H:i:s')]);
				$row_order = Db::table('orders')->where('batchcode', $batchcode['batchcode'])->update(array('last_time' => date('Y-m-d H:i:s'), 'status' => $status));
				$order_id = Db::table('orders')->where('batchcode', $batchcode['batchcode'])->value('id');
				Db::table('product')->where('id', $batchcode['product_id'])->setField('product_state', $this->change_product_state($status, $batchcode['product_id']));
			}
		} elseif ($type == 3) {
			// 退货
			$status = input('status');
			$batchcode = Db::table('orders_info')->where('id', $id)->field('batchcode,product_id,price,other_fee,original_price,nursing_cost,status')->find();
			$product = $p->check_product($batchcode['product_id']);
			$total_profit = OrderService::get_total_profit(3, $batchcode['price'], $batchcode['original_price'], $batchcode['other_fee'], $batchcode['nursing_cost'], 0, $batchcode['price']);
			$real_profit = OrderService::get_real_profit($batchcode['price'], $batchcode['original_price'], $batchcode['other_fee'], $batchcode['nursing_cost'], 0, $batchcode['price']);
			if ($batchcode['status'] == 7) {
				$date = array('code' => 28880, 'msg' => '订单已经是交易关闭状态，不需要再次退货', 'data' => '');
				exit(json_encode($date));
			}
			if (empty($status) || $status != 7) {
				$date = array('code' => 20021, 'msg' => '销售状态不能为空,且必须是交易关闭状态', 'data' => '');
				exit(json_encode($date));
			} else {
				$up = [
					'status' => 7,
					'remark' => $remark,
					'total_profit' => $total_profit,
					'real_profit' => $real_profit,
					'last_time' => date('Y-m-d H:i:s'),
				];
				$up_order = [
					'status' => 7,
					'remark' => $remark,
					'last_time' => date('Y-m-d H:i:s'),
				];
				Db::table('product')->where('id', $batchcode['product_id'])->setField('product_state', $this->change_tuihuo($batchcode['status'], $batchcode['product_id']));
				$row = Db::table('orders_info')->where('id', $id)->update($up);
				$row_order = Db::table('orders')->where('batchcode', $batchcode['batchcode'])->update($up_order);
				$order_id = Db::table('orders')->where('batchcode', $batchcode['batchcode'])->value('id');
			}
		} elseif ($type == 4) {
			$confirm = [
				'is_confirm' => 1,
				'finance_confirm_time' => date('Y-m-d H:i:s'),
			];
			$row = Db::table('orders_info')->where('id', $id)->update($confirm);
		}
		if ($row) {
			$date = array('code' => 666, 'msg' => '订单操作成功', 'data' => '');
			if ($type == 1) {
				OL::insert([
					'user_id' => $this->user_id,
					'module' => 'orders',
					'module_id' => $order_id,
					'operation_type' => 2,
					'operation_content' => json_encode(['orders' => Db::table('orders')->where(['id' => $order_id])->find(),
						'orders_info' => Db::table('orders_info')->where(['id' => $id])->find(),
						'product' => Db::table('product')->where(['id' => $batchcode['product_id']])->find(),
					]),
				]);
				OL::insert([
					'user_id' => $this->user_id,
					'module' => 'product',
					'module_id' => $batchcode['product_id'],
					'operation_type' => 2,
					'operation_content' => json_encode(['orders' => Db::table('orders')->where(['id' => $order_id])->find(),
						'orders_info' => Db::table('orders_info')->where(['id' => $id])->find(),
						'product' => Db::table('product')->where(['id' => $batchcode['product_id']])->find(),
					]),
				]);
			} elseif ($type == 3) {
				OL::insert([
					'user_id' => $this->user_id,
					'module' => 'orders',
					'module_id' => $order_id,
					'operation_type' => 2,
					'operation_content' => json_encode(['orders' => Db::table('orders')->where(['id' => $order_id])->find(),
						'orders_info' => Db::table('orders_info')->where(['id' => $id])->find(),
						'product' => Db::table('product')->where(['id' => $batchcode['product_id']])->find(),
					]),
				]);
				OL::insert([
					'user_id' => $this->user_id,
					'module' => 'product',
					'module_id' => $batchcode['product_id'],
					'operation_type' => 2,
					'operation_content' => json_encode(['orders' => Db::table('orders')->where(['id' => $order_id])->find(),
						'orders_info' => Db::table('orders_info')->where(['id' => $id])->find(),
						'product' => Db::table('product')->where(['id' => $batchcode['product_id']])->find(),
					]),
				]);
			}

		} else {
			$date = array('code' => 666, 'msg' => '没有数据需要更新', 'data' => '');
		}
		return $date;
	}

	/**
	 * 订单状态对应库存状态
	 */
	public function product_order($product_id) {

		$arr = ['1' => '3', '2' => '2', '3' => '4', '4' => '11', '5' => '5', '6' => '7', '7' => '8', '8' => '9', '9' => '10'];
		foreach ($arr as $key => $value) {
			if ($key == $status) {
				return $value;
			}
		}
	}

	/**
	 * 商品状态改变
	 * @param type $product_state
	 * @return type
	 */
	public function change_product_state($status, $product_id) {

		$product_state = Db::table('product')->where('id', $product_id)->field('product_state,is_shelf')->find();
		if ($product_state['product_state'] == 1) {
			// 商品状态:订单未到库未售
			if ($status == 1) { //待付款
				return 5; //订单未到库已售
			} elseif ($status == 2) { //待发货
				return 9; //订单未到库待发货
			} elseif ($status == 3) { //待收货
				return 13; //已发货
			} elseif ($status == 4) { //订金支付
				return 5; //订货未到库已售
			} elseif ($status == 6) { //已完成
				return 14; //售出
			} else {
				$date = array('code' => 20087, 'msg' => '不能改为此状态', 'data' => '');
				exit(json_encode($date));
			}
		} elseif ($product_state['product_state'] == 2) {
// 商品状态:在库未售
			if ($status == 1) { //待付款
				return 6; //在库已售
			} elseif ($status == 2) { //待发货
				return 10; //待发货
			} elseif ($status == 3) { //待收货
				return 13; //已发货
			} elseif ($status == 4) {
				//订金支付
				return 6;
			} elseif ($status == 5) { //平台未确认
				return 6; //已售
			} elseif ($status == 6) { //已完成
				return 14; //售出
			} else {
				$date = array('code' => 20087, 'msg' => '不能改为此状态', 'data' => '');
				exit(json_encode($date));
			}

		} elseif ($product_state['product_state'] == 3) {
			// 商品状态:库存商品护理未售
			if ($status == 1 || $status == 4) { //待付款 或定金支付
				return 7; //护理已售
			} elseif ($status == 2) { //待发货
				return 11; //护理待发货
			} elseif ($status == 3) { //待收货
				return 13; //已发货
			} elseif ($status == 5) { //平台未确认
				return 6; //已售
			} elseif ($status == 6) { //已完成
				return 14; //售出
			} else {
				$date = array('code' => 20087, 'msg' => '不能改为此状态', 'data' => '');
				exit(json_encode($date));
			}
		} elseif ($product_state['product_state'] == 4) {
			// 商品状态:暂借未售
			if ($status == 1 || $status == 4) { //待付款 或定金支付
				return 8; //暂借已售
			} elseif ($status == 2) { //待发货
				return 12; //暂借待发货
			} elseif ($status == 3) { //待收货
				return 13; //已发货
			} elseif ($status == 5) { //平台未确认
				return 6; //已售
			} elseif ($status == 6) { //已完成
				return 14; //售出
			} else {
				$date = array('code' => 20087, 'msg' => '不能改为此状态', 'data' => '');
				exit(json_encode($date));
			}
		} elseif ($product_state['product_state'] == 5) {
			// 商品状态:订货未到库已售
			if ($status == 2 || $status == 5) { //待发货 或 平台未确认
				return 9; //订单未到库待发货
			} else {
				$date = array('code' => 20087, 'msg' => '不能改为此状态', 'data' => '');
				exit(json_encode($date));
			}
		} elseif ($product_state['product_state'] == 6) {
			// 商品状态:已售
			if ($status == 2 || $status == 5) { //待发货 或 平台未确认
				return 10; //待发货
			} else {
				$date = array('code' => 20087, 'msg' => '不能改为此状态', 'data' => '');
				exit(json_encode($date));
			}
		} elseif ($product_state['product_state'] == 7) {
			// 商品状态:库存商品护理已售
			if ($status == 2 || $status == 5) { //待发货 或 平台未确认
				return 11; //护理待发货
			} else {
				$date = array('code' => 20087, 'msg' => '不能改为此状态', 'data' => '');
				exit(json_encode($date));
			}
		} elseif ($product_state['product_state'] == 8) {
			// 商品状态:暂借已售
			if ($status == 2 || $status == 5) { //待发货 或 平台未确认
				return 12; //暂借待发货
			} else {
				$date = array('code' => 20087, 'msg' => '不能改为此状态', 'data' => '');
				exit(json_encode($date));
			}
		} elseif ($product_state['product_state'] == 9 || $product_state['product_state'] == 10 || $product_state['product_state'] == 11 || $product_state['product_state'] == 12) {
			// 商品状态:待发货
			if ($status == 3) { //待收货
				return 13; //已发货
			} else {
				$date = array('code' => 20087, 'msg' => '不能改为此状态', 'data' => '');
				exit(json_encode($date));
			}
		} elseif ($product_state['product_state'] == 13) {
			// 商品状态:已发货
			if ($status == 6) { //已完成
				return 14; //售出
			} else {
				$date = array('code' => 20087, 'msg' => '不能改为此状态', 'data' => '');
				exit(json_encode($date));
			}
		} else {
			$date = array('code' => 20087, 'msg' => '该产品不在可售状态', 'data' => '');
			exit(json_encode($date));
		}
	}

	/**
	 * 销售状态为定金支付   且    定金为0
	 */

	public function check_deposit($deposit, $status) {
		if ($status == 4 && $deposit <= 0) {
			exit(json_encode(array('code' => 20088, 'msg' => '定金支付状态，定金不能为0哦', 'data' => '')));
		}
	}

	/**
	 * 编辑时可修改的状态
	 */
	public function change_status($origin_status, $new_status) {
		$arr = [
			1 => [2, 4, 5],
			4 => [2, 5],
			2 => [3, 5],
			5 => [2, 3],
			3 => [6],
		];
		foreach ($arr as $key => $value) {
			if ($key == $origin_status) {
				if (in_array($new_status, $value)) {
					return TRUE;
				} else {
					exit(json_encode(['code' => 20072, 'msg' => '订单状态不能跳级改变']));
				}
			} elseif ($new_status == 7) {
				exit(json_encode(['code' => 20721, 'msg' => '订单状态不能改变为交易关闭']));
			} elseif ($origin_status == 6) {
				exit(json_encode(['code' => 20722, 'msg' => '订单已完成，不可修改状态']));
			}
		}
	}

	/**
	 * 退货改变商品状态
	 */

	public function change_tuihuo($origin_status, $product_id) {
		$product_state = Db::table('product')->where('id', $product_id)->field('product_state,is_shelf')->find();
		if (!in_array($product_state['product_state'], [5, 6, 7, 8, 9, 10, 11, 12, 13, 14])) {
			exit(json_encode(['code' => 20720, 'msg' => '商品未售状态，不能退货', 'data' => '']));
		}
		if ($origin_status == 1) {
			exit(json_encode(['code' => 20720, 'msg' => '订单未支付，不能退货', 'data' => '']));
		} elseif ($origin_status == 6) {
			exit(json_encode(['code' => 20720, 'msg' => '订单已完成，不能退货', 'data' => '']));
		}
		if ($product_state['product_state'] == 5 || $product_state['product_state'] == 9) { //订货未到库已售/待发货
			return 1; //订货未到库未售
		} elseif ($product_state['product_state'] == 6 || $product_state['product_state'] == 10) { //已售/待发货
			return 2; //在库未售
		} elseif ($product_state['product_state'] == 7 || $product_state['product_state'] == 11) { //护理已售/护理待发货
			return 3; //  护理未售
		} elseif ($product_state['product_state'] == 8 || $product_state['product_state'] == 12) { //暂借已售/待发货
			return 4; //  暂借未售
		} elseif ($product_state['product_state'] == 13 || $product_state['product_state'] == 14) { // 已发货/售出
			return 15; //  退货未到库
		}
	}
}